import React from 'react';
import { connect } from 'dva';
import { Picker,Drawer, List, NavBar,Icon, InputItem , TabBar,DatePicker ,Toast ,Button,TextareaItem,WhiteSpace} from 'antd-mobile';
import { createForm } from 'rc-form';
import Reset from '../../style/ResetInput.less'
import { Link } from 'dva/router';
import style from '../../style/App.less'
import reqwest from 'reqwest';
import {numvail,selectvail} from '../../utils/Validator.js'
import options from '../../models/CityData.js'
import PropTypes from 'prop-types';
import {range,disabledDate,disabledDateTime } from '../../utils/Date.js'
import moment from 'moment';
import 'moment/locale/zh-cn';
const maxTime = moment('22:00 +0800', 'HH:mm Z').utcOffset(8);
const minTime = moment('08:30 +0800', 'HH:mm Z').utcOffset(8);
class OrderEdit extends React.Component{
		constructor(props){
		super(props);
		this.state={
			reginos:[],
			disable:true,
			list:JSON.parse(window.sessionStorage['ism']),
      companies:sessionStorage['companies']===undefined||sessionStorage['companies']=='undefined'?[]:JSON.parse(sessionStorage['companies']),
      material:sessionStorage['material']===undefined||sessionStorage['material']=='undefined'?[]:JSON.parse(sessionStorage['material']),
      // store_tree:sessionStorage['store_tree']===undefined?[]:JSON.parse(sessionStorage['store_tree']),
		}
	}
	loadServer(params={}){
		console.log(params)
		const _this = this;
    return
		reqwest({
      url: window.host+'/api/orders/'+_this.state.list.id,
      method: 'post',
      crossOrigin: true,
      type: 'json',
      data:{ access_tokDashBorden:localStorage['token'],
        id:_this.props.location.query.clue,
        order:{expected_square:params.square,booking_date:params.booking_date,cgj_company_id:params.cgj_company_id[0],material:JSON.parse(params.material[0]).a,material_id:JSON.parse(params.material[0]).b},
        customer:{name:params.contact,tel:params.phone,province:params.province[0],city:params.province[1],area:params.province[2],street:params.address,}
      }
    }).then((data) => {
      if(data.status=='success'){
          Toast.success(
          '保存成功',
          1,
          ()=>{
            // window.localStorage['token']=data.token;
            // window.localStorage['curloe']=data.current_user.role;
            // // debugger
            // window.localStorage['menu']=JSON.stringify(data.menu);
            // window.localStorage['cgj_id']=data.current_user.cgj_user_id;
            // window.localStorage['account_type']=data.current_user.account_type;
            // window.localStorage['userrr_id']=data.current_user.id;
            window.location.hash='/hfive/orders';
          }
        )
        
      }else{
        Toast.fail(
          data.msg,
          1
        )
      }
    }).fail( (err, msg) =>{
       Toast.offline('网络连接失败!!!', 1);
    });
	}
	handleSubmit(e){
		e.preventDefault();
    let _this=this;
    // this.props.form.getFieldError('cha_name')
    this.props.form.validateFields((err, values) => {
        // console.log(this.state.payMethods.match(/\d+/g));
        // let chaname= values.chaname!==undefined?values.chaname.match(/\d+/g):null;
        console.log(values)
      if (!err  ) {
        console.log('Received values of form: ', values);
      	_this.loadServer(values)
      }
    });
	}
	componentWillMount(){
		// let _regions=[];
		// if(!!sessionStorage['regions']){
		// 	JSON.parse(sessionStorage['regions']).map(function(data,index){
		// 		_regions.push({
		// 			value:data.id,
		// 			label:data.name
		// 		})
		// 	})
		// }
		// this.setState({reginos:_regions})
	}
	render(){
		console.log(this.state.list)
		const { getFieldProps , getFieldError} = this.props.form;
		const _this =this;
    const _companies =[];
    const _material=[];
    this.state.companies.map(function(data,index,obj){
      _companies.push({
        label:data.name,
        value:data.id
      })
    })
    this.state.material.map(function(data,index,obj){
      _material.push({
        label:data.name,
        value:'{"a":"'+data.name+'","b":"'+data.id+'"}'
      })
    })
		return(
			<div className={`${style.layout}`}>
				<List className={`${Reset.tel_list_header}`} renderHeader={() => '订单信息'}>
          <Picker className={`${Reset.tel_picker}`} data={_companies} cols={1} {...getFieldProps('cgj_company_id',{
            initialValue:[this.state.list.company_id],
          })} className="forss">
            <List.Item className={`${Reset.list_extra} ${Reset.tel_input}`} arrow="horizontal">品牌商</List.Item>
          </Picker>
          <Picker className={`${Reset.tel_picker}`} data={_material} cols={1} {...getFieldProps('material',{
            initialValue:["{a:"+this.state.list.material+",b:"+this.state.list.material_id+"}"],
          })} className="forss">
            <List.Item className={`${Reset.list_extra} ${Reset.tel_input}`} arrow="horizontal">材质</List.Item>
          </Picker>
          <InputItem
            className={`${Reset.tel_input}`}
	          clear
	          error={!!getFieldError('contact')}
	          onErrorClick={() => {
	            alert(getFieldError('contact').join('、'));
	          }}
            {...getFieldProps('contact',{
            	initialValue:this.state.list.name,
            	rules:[{required:true,message:'客户姓名'}]
            })}
            placeholder="客户姓名"
          >联系人</InputItem>
          <InputItem
            className={`${Reset.tel_input}`}
	          clear
	          error={!!getFieldError('phone')}
	          onErrorClick={() => {
	            alert(getFieldError('phone').join('、'));
	          }}
            {...getFieldProps('phone',{
            	initialValue:this.state.list.tel,
            	rules:[{required:true,message:'请输入手机号码',len:11,validator:(rule,value,callback)=>{
								!!value?numvail(rule,value.replace(/\s+/g, ""),callback):callback('请输入手机号码')
							}}]
            })}
            type='phone'
            placeholder="手机号码"
          >手机号码</InputItem>
          <DatePicker
            className={`${Reset.tel_picker}`}
            mode="date"
            title="选择日期"
            extra="预约测量时间"
            clear
            error={!!getFieldError('booking_date')}
            onErrorClick={() => {
              alert(getFieldError('booking_date').join('、'));
            }}
            minDate={moment('2016-08-06 +0800', 'YYYY-MM-DD Z').utcOffset(8)}
            {...getFieldProps('booking_date', {

            })}
          >
            <List.Item className={`${Reset.list_extra} ${Reset.tel_input}`} arrow="horizontal">测量时间</List.Item>
          </DatePicker>
          <InputItem
            className={`${Reset.tel_input}`}
            clear
            error={!!getFieldError('size')}
            onErrorClick={() => {
              alert(getFieldError('square').join('、'));
            }}
            {...getFieldProps('size',{
              initialValue:this.state.list.square,
              rules:[{required:true,message:'请输入面积'}]
            })}
            placeholder='面积'
          >面积</InputItem>
          <Picker className={`${Reset.tel_picker}`}   extra={<span>地址</span>} style={{textAlign:'left'}} clear
            error={!!getFieldError('province')}
            onErrorClick={() => {
              alert(getFieldError('province').join('、'));
            }}
            placeholder="选择地址"
            onOk={(e)=>{this.setState({disable:false});console.log(e)}}
            {...getFieldProps('province',{
              initialValue:[this.state.list.province,this.state.list.city,this.state.list.area],
              rules:[{required:true,message:'请选择地址'}]
            })}  title="选择地址" data={options} >
            <List.Item arrow="horizontal"
              className={`${Reset.list_extra} ${Reset.tel_input}`}
            >选择地址</List.Item>
          </Picker>
          <InputItem
            className={`${Reset.tel_input}`}
	          clear
	          error={!!getFieldError('address')}
	          onErrorClick={() => {
	            alert(getFieldError('address').join('、'));
	          }}
            {...getFieldProps('address',{
            	initialValue:this.state.list.street,
            	rules:[{required:true,message:'请输入地址'}]
            })}
            placeholder='地址'
          >地址</InputItem>
          <List className={`${Reset.tel_list_header}`} renderHeader={() => '介绍人'} style={{background:'#f5f5f9'}}>
            <InputItem
              className={`${Reset.tel_input}`}
              {...getFieldProps('introducer_name', {
              })}
            >介绍人</InputItem>
            <InputItem
              className={`${Reset.tel_input}`}
              {...getFieldProps('introducer_tel', {
              })}
            >电话号码</InputItem>
          </List>
          <List className={`${Reset.tel_list_header}`} renderHeader={() => '备注'} style={{background:'#f5f5f9'}}>
	          <TextareaItem
	            {...getFieldProps('count', {
	              initialValue: '备注'
	            })}
	            rows={5}
	            count={100}
	          />
	        </List>
        </List>
        <Button className={`${Reset.btn_moblie} ${Reset.tel_btn}`} onClick={this.handleSubmit.bind(this)}  type='primary'>保存</Button>
        <WhiteSpace size="sm" />
			</div>
	 	)
		
	}
}

const OrderForm = createForm()(OrderEdit);
export default connect()(OrderForm)